<?php declare(strict_types=1);

namespace Distributed\Event;

use Distributed\Contract\IEvent;
use UntilDistributed\Log;
use Exception;
use Distributed\Group\TransGroupManage;
use Communication\TxSocketData;
use Distributed\Constant;

class BegainTrancestation extends AbstractEvent implements IEvent
{
	/**
	 * 
	 * {@inheritDoc}
	 * @see \Distributed\Contract\IEvent::parseEvent()
	 */
	public function parseEvent(int $fd): ?TxSocketData
	{
		$groupId = $this->data->transGroup->groupId;
		
		try
		{
			Log::getInstance()->info("txmanage add group info");
			
			if(empty($groupId)){
				throw new Exception("Error Processing Request", 10001);
			}
			//判断是否有事务
			$transStatus = TransGroupManage::getInstance()->getGroupStatus($groupId);
			if($transStatus){
				throw new Exception("groupid conflict", 1);
			}
			$this->data->transaction->fd = $fd;
			//添加事务组(redis存储)
			$res = TransGroupManage::getInstance()->saveTransGroup($this->data->transGroup, $this->data->transaction);
			
// 			$this->dbPoolInsert();
			
			if($res){
				Log::getInstance()->error("add group right");
			}else{
				throw new Exception("add transGroup error",1);
			}
			return TxSocketData::createResponse(Constant::$tx_complete_ok);
		}
		catch(Exception $e)
		{
			var_dump($e->getMessage());
			Log::getInstance()->error($e->getMessage());
			return TxSocketData::createResponse(Constant::$tx_complete_fail);
		}
	}
	
// 	private function dbPoolInsert(): void
// 	{
// 		$redis = RedisHash::getRedis();
		
// 		$dbPool = $redis->get('db_pool');
		
// 		RedisHash::hSet('db_pool', $this->data->data['db_pool'], $this->data->data['db_pool']);
// 	}
}